package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Teacher;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;

public class OtherTeacherDao02 implements BaseTeacherDao {
    private static ArrayList<Teacher> teachers = new ArrayList<>();


    static {
        try {
            BufferedReader br=new BufferedReader(new FileReader("StudentServer\\tea1.txt"));
            String len;
            StringBuilder sb=new StringBuilder();
            while ((len=br.readLine())!=null){
                sb.append(len+" ");
            }
            //System.out.println(sb.toString());
            String strTea = sb.toString();
            String[] split = strTea.split(" ");
            for (int i = 0; i < split.length; i++) {
                String[] teaArr = split[i].split(",");
                Teacher teacher=new Teacher(teaArr[0],teaArr[1],teaArr[2],teaArr[3]);
                teachers.add(teacher);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addTeacher(Teacher teacher) {
        boolean add = teachers.add(teacher);
        reSave();
        return add;

    }

    public Teacher[] findAllTeacher() {
        Teacher[] teacher = new Teacher[teachers.size()];
        for (int i = 0; i < teachers.size(); i++) {
            Teacher teacher1 = teachers.get(i);
            teacher[i] = teacher1;
        }
        return teacher;
    }

    public void deleteTeacher(String sid) {
        int index = getIndex(sid);
        teachers.remove(index);
        reSave();
    }


    public void updateTeacher(String sid, Teacher teacher) {
        int index = getIndex(sid);
        teachers.set(index, teacher);
        reSave();
    }


    public int getIndex(String sid) {
        int index = -1;
        Teacher[] t = new Teacher[teachers.size()];
        Teacher[] tea = OtherTeacherDao02.teachers.toArray(t);
        for (int i = 0; i < tea.length; i++) {
            Teacher teacher = tea[i];
            if (teacher != null && sid.equals(teacher.getSid())) {
                index = i;
            }
        }
        return index;
    }

    public void reSave() {
        try {
            BufferedWriter bw=new BufferedWriter(new FileWriter("StudentServer\\tea1.txt"));
            for (Teacher teacher : teachers) {
                String string = teacher.toString();
                bw.write(string);
                bw.newLine();
                bw.flush();
            }
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
